import 'package:moment_dart/moment_dart.dart';
import 'package:spendbook/common/constants.dart';
import 'package:spendbook/models/model.dart';

class Project extends Model<Project> {
  @override
  String url = '/project';

  String name = '';

  double _rate = 3.8;

  double _fee = 0.00;

  double _income = 0.00;

  Moment startTime = Moment.now();

  Moment _endTime = Moment.now().add(Duration(days: 30));

  set endTime(Moment value) {
    _endTime = value;
    _computedIncome();
  }

  Moment get endTime {
    return _endTime;
  }

  set rate(dynamic value) {
    _rate = formatDouble(value, def: 3.8);
    _computedIncome();
  }

  get rate {
    return _rate;
  }

  get scopeTime {
    return startTime.ll + '至' + endTime.ll;
  }

  set fee(dynamic value) {
    _fee = formatDouble(value);
    _computedIncome();
  }

  get fee {
    return _fee;
  }

  set income(dynamic value) {
    _income = formatDouble(value);
  }

  get income {
    return _income;
  }

  @override
  void fromJson(Map<String, dynamic> json) {
    name = json['name'];
    rate = json['rate'];
    fee = json['fee'];
    income = json['income'];
    startTime = Moment.parse(json['startTime']);
    endTime = Moment.parse(json['endTime']);
    super.fromJson(json);
  }

  @override
  Map<String, dynamic> toJson() => {
        'name': name,
        'rate': rate,
        'income': income,
        'fee': fee,
        'startTime': startTime.format('YYYY-MM-DD HH:mm:ss'),
        'endTime': endTime.format('YYYY-MM-DD HH:mm:ss'),
      }..addAll(super.toJson());

  _computedIncome() {
    income = _fee * (_rate / 100) * (daysBetween(endTime.date, startTime.date) / 365);
  }
}
